package com.linxin.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linxin.reggie.common.CustomException;
import com.linxin.reggie.entity.Category;
import com.linxin.reggie.entity.Dish;
import com.linxin.reggie.entity.Setmeal;
import com.linxin.reggie.mapper.CategoryMapper;
import com.linxin.reggie.service.CategoryService;
import com.linxin.reggie.service.DishService;
import com.linxin.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Category 服务层实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类, 需要判断分类是否关联菜品或者套餐
     *
     * @param ids
     */
    @Override
    public void remove(Long ids) {
        // 在dish表中查询是否有 ids 的分类
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 等值查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, ids);
        // 统计数据
        int dishCount = dishService.count(dishLambdaQueryWrapper);
        // 有则处理关联
        if (dishCount > 0) {
            // 有菜品关联, 抛出对应的业务异常
            // 抛出自定义异常, 在全局异常处理器捕获
            throw new CustomException("该分类有菜品关联, 不能删除!!!");

        }

        // 在setmeal表中查询是否有 ids 的分类
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 等值查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, ids);
        // 统计数据
        int setmealCount = setmealService.count(setmealLambdaQueryWrapper);
        // 有则处理关联
        if (setmealCount > 0) {
            // 有套餐关联, 报错对应的业务异常
            // 抛出自定义异常, 在全局异常处理器捕获
            throw new CustomException("该分类有套餐关联, 不能删除!!!");
        }

        // 没有菜品或者套餐关联, 直接删除
        // 调用父类的删除方法
        super.removeById(ids);

    }
}
